import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入store对象
import store from '@/store'
// 导入登录注册组件
import Reg from '@/views/Reg/Reg.vue'
import Login  from '@/views/Login/Login.vue'

// 导入后台主页组件
import Main from '@/views/Main/Main.vue'
// 1. 导入 Home 组件
import Home from '@/views/Menus/Home/Home.vue'
// 导入UserInfo 组件
import UserInfo from '@/views/Menus/User/UserInfo.vue'
// 导入UserAvatar 组件
import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
// 导入UserPwd 组件
import UserPwd from '@/views/Menus/User/UserPwd.vue'
// 导入文章分类的路由组件
import ArtCate from '@/views/Menus/Article/ArtCate.vue'
// 导入文章列表的路由组件
import ArtList from  '@/views/Menus/Article/ArtList.vue'
Vue.use(VueRouter)

const routes = [
  // 配置路由规则对象
  {
    path: '/reg',
    name: 'Reg',
    component: Reg
  },
  {
    path:'/login',
    name:'Login',
    component:Login
  },
  {
    path:'/',
    name:'Main',
    component:Main,
    // 3. 开启路由重定向
    redirect: '/home',
    children: [
      // 2. home 作为 子路由规则
      { path: 'home', component: Home },
       // 用户信息的子路由规则
     { path: 'user-info', component: UserInfo },
      // 声明头像子路由规则
     { path: 'user-avatar', component: UserAvatar },
      // 声明密码子路由规则
     { path: 'user-Pwd', component: UserPwd },
      // 文章分类
     { path: 'art-cate', component: ArtCate },
     //文章列表
     { path: 'art-list', component: ArtList }
    ]
  } 
]
     
//路由守卫
// to去哪里,from来自哪里, 
// next函数 next()放行  next(false)  阻止next('路径')跳转到某个指定页面

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const token =store.state.token
  //如果用户访问/login || /reg直接放行
 /*  if(to.path === './login' || to.path === './reg'){
    next()
  }else{
    // 如果访问的不是这两个路径,看看是否有token
    if(!token){
      // 没有token就跳转到登录
      next('./login')
    }else{
      next()
    } 
    
  }*/
  
  // 如果没有token,访问的不是/login,也不是/reg
  if (!token && to.path === './login' && to.path === './reg') {
    next('./login')
  }else{
    next()
  }
})

export default router
